import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * @author chenwei
 * @Title:
 * @Package
 * @Description:
 * @date 2022/8/2517:53
 */
public class Work implements Runnable {
    /**
     * 当前Worker绑定的Selector
     */

    private final BlockingQueue<String> consumers = new LinkedBlockingQueue<>();
    private final AtomicInteger consumerCount = new AtomicInteger(0);
    private Thread workerThread;

    final void add(String msg) {
        consumers.offer(msg);
        consumerCount.incrementAndGet();
    }

    public final Thread getWorkerThread() {
        return workerThread;
    }

    @Override
    public final void run() {
        workerThread = Thread.currentThread();
        // 优先获取SelectionKey,若无关注事件触发则阻塞在selector.select(),减少select被调用次数
        try {
            String a;
            while ((a = consumers.poll()) != null) {
                System.err.println(a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}